package io.netty.myExample.duyutian.fastThreadLocal测试;

import io.netty.util.concurrent.FastThreadLocal;

import java.util.ArrayList;

/**
 * @author duyutian
 * @version 1.0
 * @date 2020/6/17 14:46
 * 比较jdk自带的Local和netty的FastThreadLocal
 */
public class CompareTheadLocalAndFastThreadLocal {
    /**
     * 进行count次添加和查询
     */
    static int count = 1000000;

    public static void main(String[] args) {
        ArrayList<ThreadLocal<String>> theadLocalList = new ArrayList<ThreadLocal<String>>();
        ArrayList<FastThreadLocal<String>> fastTheadLocalList = new ArrayList<FastThreadLocal<String>>();
        for (int i = 0; i < count; i++) {
            FastThreadLocal<String> local = new FastThreadLocal<String>();
            ThreadLocal<String> threadLocal = new ThreadLocal<String>();
            theadLocalList.add(threadLocal);
            fastTheadLocalList.add(local);
        }
        long start1 = System.currentTimeMillis();
        testLocal(theadLocalList);
        long end1 = System.currentTimeMillis();
        System.out.println("local : " + (end1 - start1));
        long start2 = System.currentTimeMillis();
        testFastLoacl(fastTheadLocalList);
        long end2 = System.currentTimeMillis();
        System.out.println("fastLocal : " + (end2 - start2));
    }

    private static void testFastLoacl(ArrayList<FastThreadLocal<String>> fastTheadLocalList) {
        for (FastThreadLocal<String> item : fastTheadLocalList) {
            item.set("haha");
        }
        for (FastThreadLocal<String> item : fastTheadLocalList) {
            item.get();
        }
    }

    private static void testLocal(ArrayList<ThreadLocal<String>> theadLocalList) {
        for (ThreadLocal<String> item : theadLocalList) {
            item.set("haha");
        }
        for (ThreadLocal<String> item : theadLocalList) {
            item.get();
        }
    }


}
